<template>
  <el-card shadow="never">
    <ZwSearchForm row-num="4" :option="searchOption" @search="search" @reset="reset"></ZwSearchForm>
    <ZwTable ref="tableRef" :pageSizes="[15, 25, 50, 100]" class="table-box" :option="tableOption" :fetch-params="state.searchParams" :fetch-api="fetchApi()" @select-all="onSelectAll" @select="onSelect">
      <template #headerOperate>
        <el-dropdown @command="handleCommand">
          <el-button type="primary" :divided="form_data.records_id.length != 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :disabled="form_data.records_id.length == 0" :command="1">批量同意</el-dropdown-item>
              <el-dropdown-item :disabled="form_data.records_id.length == 0" :command="2">批量拒绝</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </ZwTable>
  </el-card>

  <Dialog :appDialog="appDialog">
    <el-form ref="ruleFormRef" :model="form_data" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="申请人：">
        <p>
          <span>{{ applicat.length > 0 ? applicat[0].apply_work_user_name : '--' }}</span>
          <span v-if="applicat.length > 1">
            等
            <span style="color: #ff6b00">{{ applicat.length }}</span>
            申请人
          </span>
        </p>
      </el-form-item>
      <el-form-item label="拒绝原因：" prop="reason" v-if="type != 1">
        <el-input v-model="form_data.reason" type="textarea" maxlength="50" show-word-limit />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="tsx">
  import { ref, reactive, computed, render } from 'vue'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZwTable from '@/components/zw/table/Table'
  import Dialog from '@/components/Dialog.vue'
  import { deepCopy } from '@/utils/helper'
  import { checkList, batAgree, batReject } from './api'
  import { div } from '@/utils/math'
  import { ElButton, ElImage, ElIcon, ElMessage, ElPopover, ElTag, ElTooltip } from 'element-plus'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { ArrowDown } from '@element-plus/icons-vue'
  import enterprise_icon from '@/assets/customer/enterprise.png'
  import wx_one from '@/assets/common/no_weixin.png'
  import wx_tow from '@/assets/common/weixin.png'
  import wx_three from '@/assets/common/application_weixin.png'
  import { imagesInfo } from '@/api/concreation'
  import { getSetionId } from '@/utils/utils'

  const ruleFormRef = ref()
  const applicat = ref([])
  const type = ref()
  const dialogId = ref([])
  const enterprise_title = ref({
    apply_enterprise: '',
    applicat: ''
  })
  const defaultParams = reactive({
    // audit_uid: [],
    apply_uid: [],
    created_at: []
  })
  const form_data = ref({
    records_id: [],
    reason: '不好意思，暂不需要协助人'
  })
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const weixin_icon = reactive([
    { id: 0, icon: wx_one, text: '未添加' },
    { id: 1, icon: wx_tow, text: '已添加' },
    { id: 2, icon: wx_three, text: '申请中' }
  ])
  const rules = reactive({
    reason: [{ required: true, message: '请填写拒绝原因', trigger: 'blur' }]
  })
  const searchOption = computed(() => {
    return [
      {
        label: '申请人',
        name: 'apply_uid',
        value: [],
        type: 'select',
        placeholder: '请选择申请人',
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        multiple: true,
        formatOption: (v: any) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '申请时间',
        name: 'created_at',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
      }
    ]
  })
  const tableOption = [
    {
      type: 'selection',
      width: 55,
      fixed: 'left',
      selectable(row, index) {
        return row.state == 1
      }
    },
    {
      label: '客户信息',
      width: 250,
      render({ row, column, index }) {
        const slotError = () => (
          <div class="image_slot">
            <ElIcon>
              <IconPicture />
            </ElIcon>
          </div>
        )
        const reference = () => <span class="look">查看</span>
        const view = () => {
          return row.corp_contacts.map((item: any, index: number) => {
            return (
              <>
                <div class="view" style={viewStyle}>
                  <ElImage style={imgStyle} vSlots={{ error: slotError }} src={item.avatar} />
                  <div style="width: 100%; margin-left:4px">
                    <p style="display:flex; align-items: center; justify-content: space-between">
                      <span>{item.name}</span>
                      <p style="display:flex; align-items: center;">
                        {weixin_icon.map((i: any) => {
                          return (
                            <>
                              <img v-show={item.add_status == i.id} style="width:16px; height: 16px" src={i.icon} />
                              <span style="margin-left: 4px;color:#969696;font-size: 12px" v-show={item.add_status == i.id}>
                                {i.text}
                              </span>
                            </>
                          )
                        })}
                      </p>
                    </p>
                    <p style="font-size: 12px; color:#969696">上次跟进时间：{item.last_follow_time ? item.last_follow_time : '--'}</p>
                  </div>
                </div>
                <div style="border-bottom: 1px solid #EAEAEA" v-show={row.corp_contacts.length - 1 != index}></div>
              </>
            )
          })
        }
        return (
          <div class="custObj" style="display:flex; align-items: center">
            <ElImage class="custObj_avatar" vSlots={{ error: slotError }} src={row.avatar} />
            <div class="enterprise_info">
              <ElTooltip placement="top-start" content={row.name}>
                <p style="width: 93px; overflow: hidden; text-overflow: ellipsis; white-space:nowrap;">{row.name}</p>
              </ElTooltip>

              <p style="display:flex; align-items:center">
                <span class="num">共{row.corp_contacts.length}个联系人</span>
                <div v-show={row.corp_contacts.length != 0}>
                  <ElPopover placement="right" vSlots={{ reference, default: view }} width={'15%'} trigger="click"></ElPopover>
                </div>
                <p class="look2" v-show={row.corp_contacts.length == 0}>
                  查看
                </p>
              </p>
            </div>
          </div>
        )
      }
    },
    {
      // prop: 'tags',
      label: '客户标签',
      width: 200,
      isTag: true,
      // showOverflowTooltip: true
      render({ row, column, index }) {
        const Reference = () => (
          <div>
            {row.tags.map((item: any, index: any) => {
              if (index <= 5) {
                return (
                  <ElTag type="warning" size="small" style="margin: 0px 3px 5px 3px">
                    {item.name}
                  </ElTag>
                )
              }
            })}
          </div>
        )
        const Default = () => (
          <div>
            {row.tags.map((item: any) => {
              return (
                <ElTag type="warning" size="small" style="margin: 0px 3px 5px 3px">
                  {item.name}
                </ElTag>
              )
            })}
          </div>
        )
        return (
          <div>
            <div vShow={row.tags.length == 0}>--</div>
            <div vShow={row.tags.length >= 5}>
              <ElPopover
                popper-class="popGroup"
                trigger="hover"
                vSlots={{ reference: Reference, default: Default }}
                width={300}
                popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
              ></ElPopover>
            </div>
            <div vShow={row.tags.length <5 && row.tags.length != 0  }>
              <Reference></Reference>
            </div>  
          </div>
        )
      }
    },
    {
      label: '归属员工',
      width: 180,
      render({ row }) {
        const reference = (
          <div>
            <span>{row.audit_work_user_name} - </span>
            <span>{row.audit_work_user_depart.length != 0 ? row.audit_work_user_depart[0].name : ''}</span>
          </div>
        )
        const view = () => {
          return (
            <p>
              <span>{row.audit_work_user_name} - </span>
              {row.audit_work_user_depart?.map((item: any, index: number) => {
                return (
                  <span>
                    {item.name} <span v-show={row.audit_work_user_depart.length - 1 != index}>、</span>
                  </span>
                )
              })}
            </p>
          )
        }
        return <ElPopover v-show={row.audit_work_user_depart.length != 0} vSlots={{ reference, default: view }} width={'15%'} trigger="hover"></ElPopover>
      }
    },
    {
      label: '协助申请人',
      width: 180,
      render({ row }) {
        const reference = (
          <div>
            <span>{row.apply_work_user_name} - </span>
            <span>{row.apply_work_user_depart.length != 0 ? row.apply_work_user_depart[0].name : ''}</span>
          </div>
        )
        const view = () => {
          return (
            <p>
              <span>{row.apply_work_user_name} - </span>
              {row.apply_work_user_depart?.map((item: any, index: number) => {
                return (
                  <span>
                    {item.name} <span v-show={row.apply_work_user_depart.length - 1 != index}>、</span>
                  </span>
                )
              })}
            </p>
          )
        }
        return <ElPopover v-show={row.apply_work_user_depart.length != 0} vSlots={{ reference, default: view }} width={'15%'} trigger="hover"></ElPopover>
      }
    },
    {
      prop: 'remark',
      label: '拒绝原因',
      width: 280,
      showOverflowTooltip: true,
      render({ row }) {
        return <p>{row.remark ? row.remark : '--'}</p>
      }
    },
    {
      prop: 'created_at',
      label: '申请时间',
      minWidth: 180
    },
    {
      label: '操作',
      width: 160,
      isOperate: true,
      fixed: 'right',
      render({ row, column, index }) {
        return (
          <div>
            <ElButton size="small" disabled={row.state != 1} class="sopBtn" onClick={() => handleCommand(1, row)}>
              同意
            </ElButton>
            <ElButton size="small" disabled={row.state != 1} class="sopBtn" onClick={() => handleCommand(2, row)}>
              拒绝
            </ElButton>
          </div>
        )
      }
    }
  ]

  const fetchApi = () => {
    // 获取文件列表
    return checkList
  }
  // 查询按钮
  const search = (data: any) => {
    state.searchParams = deepCopy(data)
  }
  // 清空
  const reset = (v?: any) => {
    state.searchParams = deepCopy(defaultParams)
  }
  // 选中表格 checkbox
  const onSelect = (selection: any) => {
    form_data.value.records_id = getSetionId('id', selection)
    applicat.value = selection
    console.log(applicat.value, "jingjing")
  }
  // 全选
  const onSelectAll = (selection: any) => {
    form_data.value.records_id = getSetionId('id', selection)
    applicat.value = selection
  }

  const cancelHandel = (n?: number, text?: string, id: any) => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    // form_data.value.records_id = []
    if (n == 1) {
      reset()
      ElMessage.success(text)
    }
    appDialog.visible = false
  }
  const submitHandel = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        console.log(form_data.value, 'submit')
        if (type.value == 1) {
          batAgree(dialogId.value.length !=form_data.value)
            .then((res: any) => {
              form_data.value.records_id = []

              cancelHandel(1, '操作成功')
            })
            .catch((e: any) => {
              cancelHandel()
            })
        } else if (type.value == 2) {
          batReject(form_data.value)
            .then((res: any) => {
              form_data.value.records_id = []
              cancelHandel(1, '操作成功')
            })
            .catch((e: any) => {
              cancelHandel()
            })
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  const appDialog = reactive({
    visible: false,
    title: '协助人我的申请审核',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
  })
  const handleCommand = (command: any, row: any) => {
    switch (command) {
      case 1:
        if (!row.id) {
          appDialog.title = '批量同意'
        } else {
          appDialog.title = '同意'
          // dialogType.value = 1
        }
        break
      case 2:
        if (!row.id) {
          appDialog.title = '批量拒绝'
        } else {
          appDialog.title = '拒绝'
          dialogType.value = 1
        }
        break
    }
    if (row.id) {
      applicat.value = [{ apply_work_user_name: row.apply_work_user_name }]
      dialogId.value = [row.id]
    }
    type.value = command
    appDialog.visible = true
  }
  const viewStyle = {
    display: 'flex',
    ['align-items']: 'center',
    padding: '16px 0px'
  }
  const imgStyle = {
    width: '36px',
    height: '34px',
    ['text-align']: 'center',
    ['line-height']: '34px',
    ['border-radius']: '4px'
  }
</script>

<style scoped lang="scss">
  :deep .enterprise_info {
    :nth-child(1) {
      font-size: 14px;
      color: #33302d;
    }
    :nth-child(2) {
      .num {
        font-size: 12px;
        color: #969696;
      }
      .look {
        margin-left: 4px;
        font-size: 12px;
        color: #ff6b00;
        cursor: pointer;
      }
      .look2 {
        margin-left: 4px;
        font-size: 12px;
        color: #ff6b00;
        cursor: not-allowed;
        // cursor: pointer;
      }
    }
  }
  :deep .custObj_avatar {
    width: 34px;
    height: 34px;
    margin-right: 11px;
  }
  :deep .view {
    display: flex;
    align-items: center;
  }
  :deep .el-form-item {
    margin-bottom: 0px;
    &:last-child {
      margin-bottom: 15px;
    }
  }
</style>
